package com.yjt.sousou.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.permissionx.guolindev.PermissionX;
import com.yjt.sousou.R;
import com.yjt.sousou.camera.CameraActivity;
import com.yjt.sousou.create.CreateConst;
import com.yjt.sousou.create.PicRecycleAdapter;
import com.yjt.sousou.create.entity.ImageItem;
import com.yjt.sousou.utils.GifSizeFilter;
import com.yjt.sousou.utils.Glide4Engine;
import com.yjt.sousou.utils.MediaUtils;
import com.yjt.sousou.utils.WheelViewUtil;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 作者：83734
 * 时间：2018/11/27
 * 描述：
 */
public abstract class BaseCreateOrderActivity extends BaseActivity {
    protected PopupWindow mPop;
    protected ArrayList<ImageItem> mImgData = new ArrayList<>();
    protected PicRecycleAdapter mPicAdapter;
    protected MediaUtils mMediaUtils;
    protected boolean isCancel;
    protected String duration;
    protected String mAudioPath = "";
    protected MediaPlayer mMediaPlayer;


    protected void initAudio() {
        mMediaUtils = new MediaUtils(this);
        mMediaUtils.setRecorderType(MediaUtils.MEDIA_AUDIO);
        mMediaUtils.setTargetDir(getFile());
        mMediaUtils.setTargetName(UUID.randomUUID() + ".mp3");
    }
    public  Uri getImageUri(String path) {
        Uri uri = null;
        File picFile = new File(path);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                uri = FileProvider.getUriForFile(this,getPackageName()+".fileprovider", picFile);

            }catch (Exception e){
                e.printStackTrace();
            }
        } else {
            uri = Uri.fromFile(picFile);
        }
        return uri;
    }
    protected void playAudio(){
        if(!TextUtils.isEmpty(mAudioPath)){
            Uri audioUri = getImageUri(mAudioPath);
            if(mMediaPlayer == null){
                mMediaPlayer = MediaPlayer.create(this,audioUri);
                mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
//                        recycleMediaPlayer();
                    }
                });
            }
            if(mMediaPlayer.isPlaying()){
                mMediaPlayer.pause();
            }else {
                mMediaPlayer.start();
            }
        }
    }
    /**
     * 判断是否缺少权限
     */
    public static boolean hasPermission(Context mContexts, String permission) {
        return ContextCompat.checkSelfPermission(mContexts, permission) ==
                PackageManager.PERMISSION_GRANTED;
    }
    private File getFile(){
        File file = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            file = new File(getFilesDir() + File.separator + "audio");
        }else {
            file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "audio");
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }


    protected void showTime(View rootView){
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_time,null);
        TextView tv_cancel= view.findViewById(R.id.tv_cancel);
        TextView tv_confirm = view.findViewById(R.id.tv_confirm);
        mPop = new PopupWindow(view, 5 * mScreenWidth / 6,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        final WheelViewUtil util = new WheelViewUtil(this, view);
        util.setOnWheelViewScrollListener(new WheelViewUtil.OnWheelViewScrollListener() {
            @Override
            public void result(int year, int month, int day) {
//                selectTime = year + "." + month + "." + day;
            }
        });
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtils.i("time"+util.getCurrentDateAndTime());
                setTime(util.getCurrentDateAndTime());
                mPop.dismiss();
            }
        });
        mPop.showAtLocation(rootView, Gravity.CENTER, 0, 0);
    }
    protected abstract void setTime(String time);
    protected void showPicPop(View rootView) {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_select_pic_or_video,null);
        TextView tv_take_photo = view.findViewById(R.id.tv_take_photo);
        TextView tv_select_photo = view.findViewById(R.id.tv_select_photo);
        ImageView tv_close = view.findViewById(R.id.tv_close);
        mPop = new PopupWindow(view, 4 * mScreenWidth / 5,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        mPop.setFocusable(true);
        mPop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPop.setOutsideTouchable(true);
        mPop.showAtLocation(rootView, Gravity.CENTER, 0, 0);
        mPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                makeWindowLight();
            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPop.dismiss();
            }
        });
        tv_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionX.init(BaseCreateOrderActivity.this)
                        .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA,
                                Manifest.permission.RECORD_AUDIO)
                        .onExplainRequestReason((scope, deniedList) -> ToastUtils.showLong("即将申请的权限是程序必须依赖的权限"))
                        .onForwardToSettings((scope, deniedList) -> ToastUtils.showLong("您需要去应用程序设置当中手动开启权限"))
                        .request((allGranted, grantedList, deniedList) -> {
                            if (allGranted) {
                                mPop.dismiss();
                                startActivityForResult(new
                                        Intent(BaseCreateOrderActivity.this, CameraActivity.class), CreateConst.REQUEST_CODE_TAKE_PIC);

                            } else {
                                showToast("请检查您的相机或者录音权限~");
                            }
                        });

            }
        });
        tv_select_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PermissionX.init(BaseCreateOrderActivity.this)
                        .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                        .onExplainRequestReason((scope, deniedList) -> ToastUtils.showLong("即将申请的权限是程序必须依赖的权限"))
                        .onForwardToSettings((scope, deniedList) -> ToastUtils.showLong("您需要去应用程序设置当中手动开启权限"))
                        .request((allGranted, grantedList, deniedList) -> {
                            if (allGranted) {
                                mPop.dismiss();
                                Matisse.from(BaseCreateOrderActivity.this)
                                        .choose(MimeType.ofImage())
                                        .countable(true)
                                        .captureStrategy(new CaptureStrategy(true, "com.cxt.hd.fileprovider","test"))
                                        .capture(false)
                                        .maxSelectable(9)
                                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                        .thumbnailScale(0.85f)
                                        .imageEngine(new Glide4Engine())
                                        .forResult(CreateConst.REQUEST_CODE_CHOOSE_PIC);
                            } else {
                                showToast("请检查您的相机权限~");
                            }
                        });
            }
        });
    }

    protected int getDuration(String str) {
        String a = str.substring(0, 1);
        String b = str.substring(1, 2);
        String c = str.substring(3, 4);
        String d = str.substring(4);
        if (a.equals("0") && b.equals("0")) {
            if (c.equals("0") && Integer.valueOf(d) < 1) {
                return -2;
            } else if (c.equals("0") && Integer.valueOf(d) > 1) {
                duration = d;
                return Integer.valueOf(d);
            } else {
                duration = c + d;
                return Integer.valueOf(c + d);
            }
        } else {
            duration = "60";
            return -1;
        }

    }

    private void recycleMediaPlayer(){
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    @Override
    protected void onDestroy() {
        recycleMediaPlayer();
        super.onDestroy();
    }

}
